<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/14
 * Time: 15:01
 */

namespace App\Rep;


use App\Events\OrderChildAllDone;
use App\Models\Order;
use App\Models\OrderAudit;
use App\Models\OrderAuditLog;
use App\Models\OrderChild;
use App\Models\OrderRemark;
use App\Models\Product;
use App\Models\ProductJobType;
use App\Models\Specification;
use App\Utils\AutogenerationSerialNumber;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use function Symfony\Component\Routing\Matcher\Dumper\export;

class OrderRep
{

    /**
     * 获取订单列表
     * @param $params
     * @return mixed
     */
    public function getOrderListRep($params){
        $list = Order::Search($params)
            ->with(['color'=>function($q){
                return $q->select('id','color');
            },'product'=>function($q){
                return $q->select('id','product_name');
            },'customer'=>function($q){
                return $q->select('id','customer_name','customer_address','contact_phone');
            },'modelNumber'=>function($q){
                return $q->select('id','model_number','file_id')->with(['specification','file']);
            },'orderChild'=>function($q){
                return $q->with(['job_type','employee']);
            },'specification'=>function($q){
                return $q->select('id','specification');
            },'dealer'=>function($q){
                return $q->select('id','company_name');
            },'finish_product'=>function($q){
                return $q->select('order_id','num','warehouse_id','goods_shelf_id');
            },'admin_user'=>function($q){
                return $q->select('id','company_name');
            },'order_remark'])
            ->paginate($params['per_page']??10);
        return $list;
    }

    /**
     * 添加订单
     * @param $params
     * @return Order|array
     */
    public function createOrderRep($params){
        DB::beginTransaction();
        try {
            if(isset($params['id']) && !empty($params['id'])){
                $model = Order::where('id',$params['id'])->first();
                $model->order_number =$params['order_number'];//订单号
            }else{
                $model = new Order();
                $is_has_order_number = Order::where('order_number',$params['order_number'])->first();
                if($is_has_order_number){
                    return ['code'=>2001,'data'=>[],'msg'=>'订单号已存在！'];
                }
                $model->order_number =$params['order_number'];//订单号
                $model->user_id =$params['user_id'];//添加人
            }
//            $serialNumber = $params['serial_number'];
//            $info = Order::where('serial_number',$serialNumber)->first();
//            if($info){
//                $serialNumber = $this->automaticGenerationSerialNumberRep();
//            }
            //$model->serial_number =$serialNumber;//流水号
            $model->order_date =$params['order_date'];//订单日期
            $model->delivery_date =$params['delivery_date'];//交货日期
            $model->account_executive_id =$params['account_executive_id'];//业务员
            $model->product_id =$params['product_id'];//产品
            $model->model_number_id =$params['model_number_id'];//型号
            $model->num =$params['num']??1;//件数
            $specification = Specification::where('id',$params['specification_id'])->first();
            if(!$specification){
                $s_model = new Specification();
                $s_model->specification = $params['specification_id'];
                $s_model->save();
                $params['specification_id'] = $s_model->id;
            }
            $model->specification_id = $params['specification_id'];//规格
            $model->color_id =$params['color_id'];//颜色
            $model->direction =$params['direction'];//方向
            $model->customer_id =$params['customer_id'];//客户
            $model->receivables =$params['receivables'];//应收款
            $model->received =$params['received'];//已收款
            $model->remark =$params['remark'];//备注
            $model->emergency_procedure =$params['emergency_procedure'];//紧急程序
            $model->is_replenishment =$params['is_replenishment']??2;//是否补货订单
            $model->is_stock_up =$params['is_stock_up'];//是否备货订单
            $model->chuchangjia =$params['chuchangjia']??'';//出厂价
            $model->yue =$params['yue']??"";//余额
            $model->dealer =$params['dealer']??"";//经销商
            //是否备货
            if($params['is_stock_up'] == 1){
                $model->customer_id = 0;
            }

            $model->batch_number = $params['batch_number']??'';//生产批号
            $model->save();

            //添加订单备注
            $orderRemarkRep = new OrderRemarkRep();
            $orderRemarkRep->addOrderRemark($model->id,
                $params['mujia']??'',
            $params['mianliao']??'',
                $params['teshu']??'',
                $params['zuoweishu']??'',
                $params['haimian']??'',
                $params['chuangdianhoudu']??'',
                $params['chuangxianggaodu']??'',
                $params['pinpai']??''
            );

            //是否是补录订单
            if($params['is_replenishment'] == 1){
                //补录订单，直接加入成品库
                $seniFinishProductRep = new SemiFinishProductRep();
                $seniFinishProductRep->replenishmentAddFinishProductRep($model,$params['num'],$params['warehouse_id'],$params['goods_shelf_id']);
                $model->status = 1;//审核状态：通过
                $model->production_status = 3;//生产状态：成品
                $model->save();
            }else{
                //订单审核
                //判断审核流程，是否对订单进行审核
                $orderAuditList = self::judgeOrderAudit();
                if($orderAuditList){
                    //添加审核记录
                    self::createOrderAudit($orderAuditList,$model->id,$params['user_id'],$params['username'],$params['role_id'],$params['role_name'],$params['remark']);
                }else{
                    //审核流程为空,订单直接过审
                    $model->status = 1;
                    $model->production_status = 1;//生产状态：生产中
                    $model->save();
                }
            }

            DB::commit();
            return ['code'=>0,'data'=>$model,'msg'=>'success'];
        }catch(\Exception $e){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$e->getMessage()];
        }

    }

    /**
     * 删除订单
     * @param $params
     */
    public function delOrderRep($params){
        $model = Order::where('id',$params['id'])->first();
        $model->is_del = 1;
        $model->save();
        $order_child = OrderChild::where('order_id',$params['id'])->update(['is_del'=>1]);
        return $model;
    }

    /**
     * 审核订单
     * status 1：已审核通过2：未审核3：已审核不通过
     * @param $params
     */
    public function auditOrderRep($params){

        DB::beginTransaction();
        try{
            $model = Order::where('id',$params['id'])->first();
            if($model->status == 1){
                return ['code'=>2001,'data'=>[],'msg'=>'订单审核已通过，无需再次审核'];
            }
            $orderAuditLog = OrderAuditLog::where('order_audit_name',$params['field'])->where('order_id',$params['id'])->first();
            $field = $params['field'];
            $model->$field = $params['status'];
            //最后一道审核程序
            $orderAudit = OrderAudit::where('status',1)->orderBy('sort','desc')->first();
            $last_field = $orderAudit->field_name;
            //$count = OrderAuditLog::where('order_id',$params['id'])->where('res','<>',1)->count();
            if($field == $last_field){
                if($params['status'] == 1){
                    $model->status = 1;
                    //自动生成子订单
                    $childOrderRep = new OrderChildRep();
                    $childOrderRep->autoCreateOrderChild($model->product_id,$model->id,$model->model_number_id,$model->specification_id,$model->num);
                }
            }

            if($params['status'] == 2){
                $model->status = 3;
            }
            $model->save();
            $orderAuditLog->res = $params['status'];
            $orderAuditLog->remark = $params['remark']??'审核原因';
            $orderAuditLog->save();
            DB::commit();
            return $model;
        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$exception->getMessage()];
        }

    }


    /**
     * 在子订单完成提交的时候调用,加入半成品库
     * 查询子订单状态
     */
    public function selectOrderChildStatus($order_id){
        $count = OrderChild::where('order_id',$order_id)->where('is_del',2)->where('status','<>',1)->count();
        if(!$count){
            //加入半成品库
            $order = Order::where('id',$order_id)->first();
            $order->production_status = 2;
            $order->save();
            event(new OrderChildAllDone($order));
        }
    }

    /**
     * 获取审核订单列表
     * @param $params
     */
    public function getAuditOrderListRep($params){
        $list = Order::Audit($params)
            ->with(['color'=>function($q){
                return $q->select('id','color');
            },'product_name'=>function($q){
                return $q->select('id','product_name');
            },'customer'=>function($q){
                return $q->select('id','customer_name');
            },'modelNumber'=>function($q){
                return $q->select('id','model_number','file_id')->with(['specification','file']);
            },'dealer',
                'specification'=>function($q){
                    return $q->select('id','specification');
                },'audit_log'=>function($q){
                    $q->where('status',1);
                },'order_remark'])
            ->orderBy('status','asc')
            ->orderBy('id','desc')
            ->paginate($params['per_page']??10);
        return $list;
    }

    /**
     * 获取订单审核流程
     * @param $params
     */
    static public function getOrderAuditFlowRep(){
        return OrderAudit::where('status',1)->orderBy('sort','asc')->get();
    }


    /**
     * 判断是否对订单进行审核
     * @return bool
     */
    static function judgeOrderAudit(){
        $orderAuditList = self::getOrderAuditFlowRep();
        if($orderAuditList->count()>0){
            return $orderAuditList;
        }
        return false;
    }

    /**
     * 添加审核记录
     * @param OrderAudit $list
     * @param $order_id
     * @param $user_id
     * @param $user_name
     * @param $role_id
     * @param $role_name
     * @param $remark
     */
    static function createOrderAudit($list,$order_id,$user_id,$user_name,$role_id,$role_name,$remark){
        foreach($list as $k=>$v){
            //添加审核记录
            OrderAuditLog::updateOrCreate(['order_id'=>$order_id,'audit_name'=>$v->audit_name],
                [
                    //'order_id'=>$order_id,
                    'user_id'=>$user_id,
                    'user_name'=>$user_name,
                    'role_id'=>$role_id,
                    'role_name'=>$role_name,
                    'order_audit_name'=>$v->field_name,
                    'audit_name'=>$v->audit_name,
                    'order_audit_id'=>$v->id,
                ]);
        }
    }

    /**
     * 设置订单的生产状态
     */
    public function setOrderProductionStatus($order_id,$production_status){
        $order = Order::where('id',$order_id)->first();
        $order->production_status = $production_status;
        $order->save();
        return $order;
    }

    //自动生成流水号
    public function automaticGenerationSerialNumberRep($int = 1){
        $rule = \App\Models\RuleSerialNumber::first();
        $prefix = $rule->prefix_custom;
        if($rule->date == 1){
            $date = date("Y");
        }
        if($rule->date == 2){
            $date = date("Ym");
        }
        if($rule->date == 3){
            $date = date("Ymd");
        }
        $count = Order::whereBetween('created_at',[date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')])->count();
        $number = str_pad($count+$int,$rule->serial_number,"0",STR_PAD_LEFT);
        $serialNumber = $prefix.$date.$number;
        return $serialNumber;
    }

    //自动生成订单号
    public function automaticGenerationOrderNumberRep($int = 1){
        $order = Order::where('is_del',2)->orderBy('id','desc')->first();
//        if($order){
//            $order_number = $order->order_number;
//            //$order_number = "abcdef";
//            preg_match_all('/\d+/', $order_number, $result);
//            if(!empty($result[0])){
//                $old_num = $result[0][count($result[0])-1];
//                //p($old_num);
//                $new_num = $old_num +1;
//                $str = str_replace($old_num,$new_num,$order_number);
//                //p($str);
//            }else{
//                $str = $order_number."1";
//            }
//        }else{
//            $str='001';
//        }
        if($order){
            $order_number = $order->order_number+$int;
            $info = Order::where('order_number',$order_number)->first();
            if($info){
                $int = $int + 1;
                $order_number = $this->automaticGenerationOrderNumberRep($int);
            }
        }else{
            $order_number = 1;
        }


        return $order_number;
    }

}
